#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 crane <crane@gosun>
#
# Distributed under terms of the MIT license.

"""

"""

import numpy
import math

def online_variance(data):
    n = 0
    mean = 0.0
    M2 = 0.0

    for x in data:
        n += 1
        delta = x - mean
        mean += delta/n
        M2 += delta*(x - mean)

    if n < 2:
        return float('nan')
    else:
        print("result", M2 / (n-1))
        return M2 / (n - 1)

def online_std(oldStd, oldMean, oldCnt, oldSum, x):
    n = oldCnt + 1
    delta = x - oldMean
    # newMean = oldMean + delta/n
    newMean = (oldSum + x) / n
    newStd = oldStd + delta*(x - newMean)

    return newStd / (n - 1)

def online_std_square(oldSquareMean, oldCnt, oldSum, x):
    n = oldCnt + 1
    # delta = x - oldMean
    # oldMean = oldSum / oldCnt
    # newMean = oldMean + delta/n
    newMean = (oldSum + x) / n
    newSquareSum = (oldSquareMean * oldCnt) + x ** 2
    newSquareMean = newSquareSum / n

    newStd = math.sqrt(newSquareMean - newMean ** 2)

    return newStd


def new_mean(curCnt, curMean, augCnt, augMean):
        # // input: 原有cnt和原有的mean. 新增数据的cnt和新增数据的mean
        # // 输出新的mean
        totalCnt = curCnt + augCnt
        meanDelta = (augMean - curMean) * augCnt / totalCnt
        return curMean + meanDelta

def test():
    arr1 = [1,2,3]
    std1 = numpy.std(arr1)
    print("std1", std1)

    arr2 = [1,2,3, 4]
    std2 = numpy.std(arr2)
    print("std1", std2)

    std3 = online_std(std1, 2, 3, 6, 4)
    print("std3", std3)

    online_variance([1,2,3,4])
    # print("std3", std3)

    std5 = online_std_square(14/3, 3, 6, 4)
    print(std5)

def test_mean():
    nmean = new_mean(5, 3, 3, 2)
    print(nmean)
    print(21 / 8)

    nmean = new_mean(5, 3, 1, 2)
    print(nmean)
    print(17 / 6)

def main():
    print("start main")
    # test()
    test_mean()

if __name__ == "__main__":
    main()
